package com.starblink.wishlist.wishallitems.ui

import android.app.Activity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.*
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.GuessYouLikeProductByWishListParam
import com.starblink.rocketreserver.type.PageQuery4CollectProductReq
import com.starblink.wishlist.wishallitems.ui.bean.*
import com.starblink.wishlist.wishboards.ui.bean.*
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class WishAllItemsVM : BaseViewModel() {


    var mAllItemsObserver: MutableLiveData<ArrayList<Any>> = MutableLiveData()
    var mFilterDataObserver: MutableLiveData<ArrayList<RvFilterEntry>> =
        MutableLiveData()

    var pageTopIndex = 1
    var pageTopSize = 20
    var pageRelatedIndex = 1

    //记录feeds流总条数
    var lastFeedsSize = 0

    var searchTitleKey: String? = null

    //0 首页  1搜索复用
    var displayType = 0

    var currentPageIndex = 0

    /****************多选相关 ↓↓↓↓↓↓↓↓↓ ****************************/
    var choiceMode = false

    var selectAll = false
    var choiceNum = 0

    var recordIds = hashSetOf<String>()
    var record2Items = arrayListOf<RvBoardDetailsItemEntry>()
    /****************多选相关 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ****************************/

    /****************筛选相关 ↓↓↓↓↓↓↓↓↓ ****************************/
    var choiceFilterData = arrayListOf<RvFilterChildEntry>()
    var choiceEntry = hashMapOf<String, RvFilterEntry>()
    var choiceIndex = 0
    var choiceName = hashMapOf(0 to "Status")

    //失效状态
    val statusBean = RvFilterEntry(
        name = "Status",
        child = arrayListOf("Valid", "Invalid", "On Sale"),
        childChoice = arrayListOf(false, false, false)
    )

    val statusMap = mapOf("Valid" to 1, "Invalid" to 0, "On Sale" to 2)

    var statusParams: Int? = null

    val timeRangeBean = RvFilterEntry(
        name = "Time",
        child = arrayListOf("In 7 Days", "In 30 Days", "In 6 months", "6 months ago"),
        childChoice = arrayListOf(false, false, false, false)
    )
    val timeRangeMap =
        mapOf("In 7 Days" to 1, "In 30 Days" to 2, "In 6 months" to 3, "6 months ago" to 4)
    var timeParams: Int? = null

    //热门品牌
    var hotBrandFilterMap = arrayListOf<String>()
    var hotBrandParams: String? = null

    //前台类目
    var foregroundCategoryFilterMap = arrayListOf<String>()

    var categoryParams: String? = null


    /****************筛选相关 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ****************************/

    //召回相关
//    var hasAddRelatedTitle = false

    //暂不开启 脏数据太多 不准
    var autoLoadMore = false
    var mWishTotalNum: Int = 0
    var productCardIndex = 0

    var hasAddRelatedTitle = false
    fun initSomeData() {
        if (mAllItemsObserver.value == null) {
            mAllItemsObserver.value = arrayListOf()
        }
        if (mFilterDataObserver.value == null) {
            mFilterDataObserver.value = arrayListOf()
        }
    }

    inline fun refreshData(
        showDialog: Boolean = false,
        needFilter: Boolean = true,
        crossinline hasFinish: () -> Unit,
        activity: Activity
    ) {
        viewModelScope.launch {
            autoLoadMore = false
            pageTopIndex = 1
            mWishTotalNum = 0
            val wishResult = SkGqlClient.skQuery(
                PageQueryMyCollectProductsQuery(
                    pageQuery4CollectProduct = PageQuery4CollectProductReq(
                        wishListId = 0,
                        needFilterResultList = Optional.present(needFilter),
                        pageNo = pageTopIndex.optional(),
                        pageSize = Optional.present(pageTopSize)
                    )
                ),
                showDefaultLoading = showDialog,
                activity = activity
                //fetchPolicy = FetchPolicy.NetworkFirst
            )?.data?.pageQueryMyCollectProducts


            combineBoardsAndRelate(wishResult, filterSearch = false, hasFinish = {
                hasFinish.invoke()
            }, activity = activity)
        }
    }


    inline fun refreshFilterData(
        showDialog: Boolean = false,
        isClick: Boolean = false,
        crossinline hasFinish: () -> Unit,
        activity: Activity
    ) {
        viewModelScope.launch {

            if (isClick) {
                SkGqlClient.defaultLoadingShow(true)
            }


            autoLoadMore = false
            statusParams = null
            timeParams = null
            hotBrandParams = null
            categoryParams = null
            //解析失效参数
            choiceEntry[choiceName[0]]?.let {
                for ((index, _) in it.childChoice.withIndex()) {
                    if (it.childChoice[index]) {
                        statusParams = statusMap[it.child[index]]!!
                        break
                    }
                }
            }
            //解析时间参数
            choiceEntry[choiceName[1]]?.let {
                for ((index, _) in it.childChoice.withIndex()) {
                    if (it.childChoice[index]) {
                        timeParams = timeRangeMap[it.child[index]]!!
                        break
                    }
                }
            }
            //解析类目参数
            getCurrentCategoryOrBrandIndex(1).let { index ->
                if (index > 0) {
                    choiceEntry[choiceName[index]]?.let {
                        for ((index, _) in it.childChoice.withIndex()) {
                            if (it.childChoice[index]) {
                                categoryParams = it.child[index]
                                break
                            }
                        }
                    }
                }
            }

            //解析品牌参数
            getCurrentCategoryOrBrandIndex(2).let { index ->
                if (index > 0) {
                    choiceEntry[choiceName[index]]?.let {
                        for ((index, _) in it.childChoice.withIndex()) {
                            if (it.childChoice[index]) {
                                hotBrandParams = it.child[index]
                                break
                            }
                        }
                    }
                }
            }

            pageTopIndex = 1

            val validValue = handleStatusParams()
            val onSaleValue = handleOnSaleParams()
            val wishResult = SkGqlClient.skQuery(
                PageQueryMyCollectProductsQuery(
                    pageQuery4CollectProduct = PageQuery4CollectProductReq(
                        wishListId = 0,
                        needFilterResultList = Optional.present(false),
                        pageNo = pageTopIndex.optional(),
                        title = Optional.present(searchTitleKey),
                        pageSize = Optional.present(pageTopSize),
                        valid = Optional.presentIfNotNull(validValue),
                        timeRange = Optional.presentIfNotNull(timeParams),
                        hotBrand = Optional.presentIfNotNull(hotBrandParams),
                        foregroundCategory = Optional.presentIfNotNull(categoryParams),
                        onSale = Optional.presentIfNotNull(onSaleValue)
                    )
                ),
                showDefaultLoading = showDialog, activity = activity
                //fetchPolicy = FetchPolicy.NetworkFirst
            )?.data?.pageQueryMyCollectProducts

            combineBoardsAndRelate(wishResult, filterSearch = true, hasFinish = {
                if (isClick) {
                    SkGqlClient.defaultLoadingDismiss(true)
                }
                hasFinish.invoke()
            }, activity = activity)
        }
    }


    // 1 类目 2品牌
    fun getCurrentCategoryOrBrandIndex(type: Int): Int {
        if (type == 1) {
            if (foregroundCategoryFilterMap.size > 0) {
                return 2
            }
        } else if (type == 2) {
            if (hotBrandFilterMap.size > 0) {
                return if (foregroundCategoryFilterMap.size > 0) 3 else 2
            }
        }
        return -1
    }

    //接口迭代，这里的选中单独处理
    fun handleStatusParams(): Int? {
        if (0 == statusParams || 1 == statusParams) {
            return statusParams
        }
        return null
    }

    fun handleOnSaleParams(): Boolean? {
        if (2 == statusParams) {
            return true
        }
        return null
    }


    inline fun combineBoardsAndRelate(
        wishResult: PageQueryMyCollectProductsQuery.PageQueryMyCollectProducts?,
        filterSearch: Boolean,
        crossinline hasFinish: () -> Unit, activity: Activity
    ) {
        wishResult.let {
            mAllItemsObserver.value!!.clear()
            // 列表数据
            if (!it?.productList.isNullOrEmpty()) {
                //总条数
                if ((it?.total ?: 0) > 0) {
                    mAllItemsObserver.value!!.add(
                        RvTotalNumEntry(
                            total = it!!.total
                        )
                    )
                    mWishTotalNum = it.total
                }
                for ((index, prdList) in it!!.productList!!.withIndex()) {
                    mAllItemsObserver.value!!.add(
                        RvBoardDetailsItemEntry(
                            wishItem = prdList.productF,
                            showCheckMode = choiceMode,
                            hasChoice = if (selectAll) true else (recordIds.contains(
                                prdList.productF.id
                            )),
//                            position = mAllItemsObserver.value!!.size,
                            //注意因为my wishlist 只有这个引导才这么写！！！！！
                            //注意因为my wishlist 只有这个引导才这么写！！！！！
                            //注意因为my wishlist 只有这个引导才这么写！！！！！
                            //注意因为my wishlist 只有这个引导才这么写！！！！！
                            //注意因为my wishlist 只有这个引导才这么写！！！！！
//                            isFirst = if (filterSearch || SkStorage.getBoolean(
//                                    SkGuideEnum.WISHLIST_MORE_SETTING_1_13.name,
//                                    false
//                                )
                            isFirst = false
//                            ) false else (index == 0)
                        )
                    )
                }
            } else {
                if (filterSearch) {
                    mAllItemsObserver.value!!.add(RvFilterEmpty())
                } else {
                    mAllItemsObserver.value!!.add(RvNormalEmpty())
                }
            }

            if (!filterSearch) {
                //筛选数据
                mFilterDataObserver.value?.clear()
                //重置选择数据

                if (mWishTotalNum > 0) {
                    for ((index, item) in statusBean.childChoice.withIndex()) {
                        statusBean.childChoice[index] = false
                    }
                    for ((index, item) in timeRangeBean.childChoice.withIndex()) {
                        timeRangeBean.childChoice[index] = false
                    }

                    mFilterDataObserver.value!!.add(statusBean)
                    mFilterDataObserver.value!!.add(timeRangeBean)

                    // # 类目可选列表
                    it?.foregroundCategorySelect?.let { list ->
                        if (list.isNotEmpty()) {
                            foregroundCategoryFilterMap.clear()
                            var arr = ArrayList(list)
                            var arrChoice = arrayListOf<Boolean>()
                            for ((index, item) in arr.withIndex()) {
                                foregroundCategoryFilterMap.add(item)
                                arrChoice.add(false)
                            }

                            mFilterDataObserver.value!!.add(
                                RvFilterEntry(
                                    name = "Category",
                                    child = foregroundCategoryFilterMap,
                                    childChoice = arrChoice
                                )
                            )
                        }
                    }

                    //  # 品牌可选列表
                    it?.hotBrandSelect?.let { list ->
                        if (list.isNotEmpty()) {
                            hotBrandFilterMap.clear()
                            var arr = ArrayList(list)
                            var arrChoice = arrayListOf<Boolean>()
                            for ((index, item) in arr.withIndex()) {
                                hotBrandFilterMap.add(item)
                                arrChoice.add(false)
                            }
                            mFilterDataObserver.value!!.add(
                                RvFilterEntry(
                                    name = "Brand",
                                    child = hotBrandFilterMap,
                                    childChoice = arrChoice
                                )
                            )
                        }
                    }
                }
            }
        }
        //判断是否心愿单列表数据尚未全部取得
//        if (canLoadGuessData() && filterSearch && displayType == 0) {
        if (canLoadGuessData(filterSearch)) {
            pageRelatedIndex = 1
            productCardIndex = 0
            viewModelScope.async {
                val guessLike = SkGqlClient.skQuery(
                    GuessYouLikeProductByWishListQuery(
                        params = GuessYouLikeProductByWishListParam(
                            pageNo = 1,
                            pageSize = 20,
                            wishListId = Optional.present("0")
                        )
                    ),
                    //fetchPolicy = FetchPolicy.NetworkFirst
                    showFailToast = false,
                    showErrorToast = false,
                    activity = activity
                )?.data?.guessYouLikeProductByWishList
                if (!guessLike.isNullOrEmpty()) {
                    if (pageRelatedIndex == 1) {
                        hasAddRelatedTitle = true
                        mAllItemsObserver.value?.add(RvRelatedTitleEntry())
                    }
                    guessLike.forEach {
                        mAllItemsObserver.value?.add(
                            RvBoardProductEntry(
                                position = productCardIndex,
                                product = it.productF,
                                feedType = 3
                            )
                        )
                        productCardIndex++
                    }
                }
                mAllItemsObserver.postValue(mAllItemsObserver.value)
                hasFinish.invoke()
            }
        } else {
            mAllItemsObserver.postValue(mAllItemsObserver.value)
            hasFinish.invoke()
        }
        if (!filterSearch) {
            mFilterDataObserver.postValue(mFilterDataObserver.value)
        }
    }

//    fun addGuessItem(item: ProductF) {
//
//        if (mAllItemsObserver.value!!.size >= 2) {
//            if (mAllItemsObserver.value!![0] is RvTotalNumEntry) {
//                var numEntry = mAllItemsObserver.value!![0] as RvTotalNumEntry
//                numEntry.total = numEntry.total + 1
//            }
//
//            mAllItemsObserver.value!!.add(
//                1,
//                RvBoardDetailsItemEntry(
//                    wishItem = item,
//                    showCheckMode = choiceMode,
//                    hasChoice = if (selectAll) true else (recordIds.contains(
//                        item.id
//                    )),
////                position = index,
//                )
//            )
//            mAllItemsObserver.postValue(mAllItemsObserver.value)
//        }
//
//    }

    inline fun loadMoreData(crossinline hasFinish: () -> Unit, activity: Activity) {
        viewModelScope.launch {
            pageTopIndex++

            val validValue = handleStatusParams()
            val onSaleValue = handleOnSaleParams()
            val wishResult = SkGqlClient.skQuery(
                PageQueryMyCollectProductsQuery(
                    pageQuery4CollectProduct = PageQuery4CollectProductReq(
                        wishListId = 0,
                        needFilterResultList = Optional.present(true),
                        pageNo = pageTopIndex.optional(),
                        title = Optional.present(searchTitleKey),
                        pageSize = Optional.present(pageTopSize),
                        valid = Optional.presentIfNotNull(validValue),
                        timeRange = Optional.presentIfNotNull(timeParams),
                        hotBrand = Optional.presentIfNotNull(hotBrandParams),
                        foregroundCategory = Optional.presentIfNotNull(categoryParams),
                        onSale = Optional.presentIfNotNull(onSaleValue)
                    )
                ),
                //fetchPolicy = FetchPolicy.NetworkFirst
                activity = activity
            )?.data?.pageQueryMyCollectProducts
            wishResult.let {
                // 列表数据
                if (!it?.productList.isNullOrEmpty()) {
                    it!!.productList!!.forEach { prdList ->
                        mAllItemsObserver.value!!.add(
                            RvBoardDetailsItemEntry(
                                wishItem = prdList.productF,
                                showCheckMode = choiceMode,
                                hasChoice = if (selectAll) true else (recordIds.contains(
                                    prdList.productF.id
                                )),
//                                position = mAllItemsObserver.value!!.size
                            )
                        )
                    }
                } else {
//                    toastUI(CommUtils.getString(com.starblink.android.common.R.string.no_more_data))
                }
                mAllItemsObserver.postValue(mAllItemsObserver.value)
                hasFinish()

            }
        }
    }


    fun loadMoreGuess(hasFinish: () -> Unit, activity: Activity) {
        if (!UserDataCenter.isLogin()) {
            hasFinish.invoke()
            return
        }

        viewModelScope.launch {
            pageRelatedIndex++
            val moreRelated = SkGqlClient.skQuery(
                GuessYouLikeProductByWishListQuery(
                    params = GuessYouLikeProductByWishListParam(
                        pageNo = pageRelatedIndex,
                        pageSize = 20,
                        wishListId = Optional.present("0")
                    )
                ),
                //fetchPolicy = FetchPolicy.NetworkFirst
                showFailToast = false,
                showErrorToast = false,
                activity = activity
            )?.data?.guessYouLikeProductByWishList
            if (!moreRelated.isNullOrEmpty()) {
                if (!hasAddRelatedTitle) {
                    mAllItemsObserver.value?.add(RvRelatedTitleEntry())
                    hasAddRelatedTitle = true
                }

                moreRelated.forEachIndexed { i, prd ->
                    mAllItemsObserver.value?.add(
                        RvBoardProductEntry(
                            position = productCardIndex,
                            product = prd.productF,
                            feedType = 3
                        )
                    )
                    productCardIndex++
                }
                mAllItemsObserver.postValue(mAllItemsObserver.value)
                hasFinish.invoke()
            } else {
//                toastUI(CommUtils.getString(com.starblink.android.common.R.string.no_more_data))
                pageRelatedIndex--
                hasFinish.invoke()
            }
        }
    }


    /**
     * 1:默认进去没数据不展示推荐，2:筛选条件下不管是否有数据，都会展示推荐，3:只要有数据下拉到底就展示推荐
     */
    fun canLoadGuessData(filterSearch: Boolean): Boolean {
        if (displayType != 0) {
            return false
        }
        if (filterSearch && mAllItemsObserver.value!!.size > 0 && mAllItemsObserver.value!![0] is RvFilterEmpty && UserDataCenter.isLogin()) {
            return true
        }
        //条件1
        if (!filterSearch && mWishTotalNum == 0) {
            return false
        }
        if (filterSearch && mAllItemsObserver.value!!.size > 0 && mAllItemsObserver.value!![0] is RvFilterEmpty && UserDataCenter.isLogin()) {
            return true
        }

        if (pageTopSize * pageTopIndex >= mWishTotalNum && UserDataCenter.isLogin()) {
            return true
        }

        return false
    }


    //批量删除心愿单
    fun deleteCollItems(activity: Activity) {
        viewModelScope.launch {
            var items = arrayListOf<CollectItem>()
            record2Items.forEach { prdF ->
                prdF.wishItem.id?.let {
                    items.add(
                        CollectItem(
                            id = prdF.wishItem.id!!,
                            type = prdF.wishItem.type.optional(),
                            outOfferId = Optional.present(prdF.wishItem.outOfferId)
                        )
                    )
                }
            }
            var result = SkGqlClient.skMutation(
                CancelCollectProductListV2Mutation(
                    items = Optional.present(items)
                ),
                showDefaultLoading = true,
                activity = activity
            )?.data?.cancelCollectProductListV2

            if (result == true) {

                //这里的下标不能取0 因为用户插入是无序的 要用需要排序一次  取最小值 但是因为要刷总数 所以这里暂时用不到
//                val startIndex = record2Items[0].position

                var deleteList = mutableListOf<ProductF>()
                record2Items.forEach { prdF ->
                    mAllItemsObserver.value?.remove(prdF)
                    deleteList.add(prdF.wishItem)
                }

                //同步第一项
                mWishTotalNum -= record2Items.size
                if (mAllItemsObserver.value!!.size > 0) {
                    var numEntry = mAllItemsObserver.value!![0]
                    if (numEntry is RvTotalNumEntry) {
                        numEntry.total = mWishTotalNum
                    }
                }
                FlowBus.with<List<ProductF>>(FlowConst.WISHLIST_DELETE_PRODUCT_VIEW)
                    .post(deleteList.toList())

                record2Items.clear()
                recordIds.clear()

                mAllItemsObserver.postValue(mAllItemsObserver.value)
                FlowBus.with<Int>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_1)
                    .post(items.size)


                YYLogUtils.e(" #######startIndex11   ${0}")
            }
        }
    }

    /**
     * 刷新底部选项 同时记录选中数据
     */
    fun refreshChoiceNum(): Int {
//        if (allCheck) {
//            choiceNum = mAllItemsObserver.value!!.size
//            return choiceNum
//        }
        var num = 0
        recordIds.clear()
        record2Items.clear()
        mAllItemsObserver.value?.forEach {
            if (it is RvBoardDetailsItemEntry && it.hasChoice) {
                num++
                it.wishItem.id?.let { prdId ->
                    recordIds.add(prdId)
                    record2Items.add(it)
                }
            }
        }
        choiceNum = num
        return choiceNum
    }

    fun clearChoiceHistory() {
        selectAll = false
        recordIds.clear()
        record2Items.clear()
        choiceNum = 0
    }

    fun getCurrentItemDataSize(): Int {
        var num = 0
        mAllItemsObserver.value?.forEach {
            if (it is RvBoardDetailsItemEntry) {
                num++
            }
        }
        return num
    }
}